/**
 * Created by Administrator on 2017/3/21.
 */
import React, { Component, Fragment } from 'react';
import {Form, Button, Badge, Select, Switch, DatePicker, Descriptions, Tag, Modal, message, Input} from 'antd';
import {connect} from 'dva';
import ReactDataGrid from 'react-data-grid';
import BuildModalTitle from '@/components/BuildModalTitle';
import AddOrEditVendor from './AddOrEditVendor';
import {  afterCloseModal } from '@/utils/utils';
import request from '@/utils/request';
import AddOrEditDevice from './AddOrEditDevice';
import moment from "moment";
import AddOrEditVendorCustom from "@/pages/Vendor_meter/AddOrEditVendorCustom";
import Loading from "@/components/Loading";
const Option = Select.Option;
const { confirm } = Modal;
const ButtonGroup = Button.Group;
const FormItem = Form.Item;
class AddPoliciesForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showCustom: false,
      data:[],
      editRecord:{},
      all_vendors: [],
      loading:false,
      searchParams:{
        company_id:'',

        vendor_id:'',
        start_date:moment(new Date().getFullYear()+'-'+(parseInt(new  Date().getMonth())+1)+'-'+'01' , "YYYY-MM-DD").format("YYYY-MM-DD"),
        end_date:moment(new Date().getFullYear()+'-'+(parseInt(new  Date().getMonth())+1)+'-'+ moment().endOf('month').format('DD')).format('YYYY-MM-DD')
      }
    };
  }

  componentDidMount() {
    const that = this;
    request(`/all_vendors`, {
      method: 'GET',
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          all_vendors: response.data.data,
        });
      }

    });
   this.handleSearch(this.state.searchParams)
  }
  handleSearch=(searchParams)=>{
    const that=this;
    this.setState({
      loading:true
    })
    request(`/all_vendor_analysis_data`,{
      method:'GET',
      params:{...searchParams, order_column:'date'}}
    ).then((response)=>{
      if(response.status===200){
        that.setState({
          data:response.data.data
        })
        this.setState({
          loading:false
        })
      }

    });
  }
  handleAdd=()=>{
    const that=this;
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    request(`/vendor_analysis_data`,{
      method:'POST',
      data:{
        items:[
          {
            ...formValues,
            date:moment(formValues.date).format('YYYY-MM-DD')
          }
        ]

      }
    }).then((response)=>{
      if(response.status===200){
        that.handleSearch(this.state.searchParams)
        that.setState({
          addModal:false
        })
        message.success('添加成功')
      }
    });
  }
  handleEdit=()=>{
    const that=this;
    const formValues = this.EditForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    request(`/vendors/${this.state.editRecord.id}`,{
      method:'PUT',
      data:formValues
    }).then((response)=>{
      if(response.status===200){
        that.handleSearch(this.state.searchParams)
        that.setState({
          editModal:false
        })
        message.success('修改成功')
      }
    });
  }
  handleDelete=(id)=>{
    const that=this;
    request(`/vendor_analysis_data/${id}`,{
      method:'DELETE',
    }).then((response)=>{
      if(response.status===200){
        that.handleSearch(this.state.searchParams)
        message.success('删除成功')
      }
    });
  }
  handleFormReset = () => {
    const { form } = this.props;
    const username=sessionStorage.getItem('username')
    form.resetFields();
    let vendor_id='';
    this.handleSearch({
      company_id:'',
      vendor_id:'',
      start_date:moment(new Date().getFullYear()+'-'+(parseInt(new  Date().getMonth())+1)+'-'+'01' , "YYYY-MM-DD").format("YYYY-MM-DD"),
      end_date:moment(new Date().getFullYear()+'-'+(parseInt(new  Date().getMonth())+1)+'-'+ moment().endOf('month').format('DD')).format('YYYY-MM-DD'),
      order_column:'date'
    });
  };
  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    const searchParams=this.state.searchParams
    return (
      <Form layout="inline" className="search-form">
        {
          !sessionStorage.getItem('company_id')&&
          <FormItem label="所属分站">
            {getFieldDecorator('company_id', {
              initialValue: searchParams.company_id,
            })(
              <Select style={{ width: '120px' }} allowClear={true}>
                {
                  JSON.parse(sessionStorage.getItem('management_companies')).map((item,index)=>{
                    return <Option key={index} value={item.id}>
                      {item.name}
                    </Option>
                  })
                }
              </Select>
            )}
          </FormItem>
        }
        <FormItem label={'开始日期'}>
          {getFieldDecorator('start_date', {
            initialValue: moment(searchParams.start_date),
          })(
            <DatePicker
              style={{width: '120px'}}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />
          )}
        </FormItem>
        <FormItem label={'结束日期'}>
          {getFieldDecorator('end_date', {
            initialValue: moment(searchParams.end_date),
          })(
            <DatePicker
              style={{width: '120px'}}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />
          )}
        </FormItem>
        <FormItem label="水表厂商">
          {getFieldDecorator('vendor_id', {
            initialValue: searchParams.vendor_id,
          })(
            <Select style={{ width: '100px' }} allowClear>
              {
                this.state.all_vendors.map((item, index) => {
                  return <Option key={index} value={item.id}>{item.name}</Option>;
                })
              }
            </Select>,
          )}
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                  start_date: moment(fieldsValue.start_date).format('YYYY-MM-DD'),
                  end_date: moment(fieldsValue.end_date).format('YYYY-MM-DD'),
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
          <Button type="primary" style={{marginLeft:'10px'}} onClick={()=>{
            this.setState({
              addModal:true
            })
          }}>
            添加手工数据
          </Button>
        </FormItem>

      </Form>
    );
  }

  render() {
    const loading=this.state.loading
    const defaultColumnProperties = {
      resizable: true,
    };
    const that=this;
    const columns = [
      {
        name: '日期',
        width: 175,
        key: 'date',
      },
      {
        name: '厂商名称',
        width: 175,
        key: 'vendor_name',
      },
      {
        name: '抄读率(%)',
        width: 175,
        key: 'normal_rate',
      },
      {
        name: '操作',
        width: 125,
        key: 'right',
        classname:'operate',
        formatter: (event) => <Fragment>
            <Button
              type="danger"
              size="small"
              icon="delete"
              onClick={(e) => {
                e.stopPropagation();
                confirm({
                  title: `确定要删除"${event.row.vendor_name}"${event.row.date}抄读率吗?`,
                  content: '请谨慎操作！',
                  okText: '确定',
                  okType: 'danger',
                  cancelText: '取消',
                  centered:true,
                  maskClosable: true,
                  onOk() {
                    that.handleDelete(event.row.id);
                  },
                  onCancel() {
                    console.log('Cancel');
                  },
                });
              }
              }
            >删除
            </Button>
        </Fragment>,
      },
    ].map(c => ({  ...defaultColumnProperties,...c }));

    return (
      <div>
        <div style={{marginBottom:'10px'}}>
          {this.renderSimpleForm()}
        </div>
        <div style={{position:'relative'}}>
          <ReactDataGrid
            columns={columns}
            rowGetter={i => this.state.data[i]}
            rowsCount={this.state.data.length}
            minHeight={(this.state.data.length+1)*35+12}

          />
          {
            loading && <Loading/>
          }
        </div>
        <Modal
          title={<BuildModalTitle visible={this.state.addModal} modalClass="addModal" title="添加手工数据"/>}
          visible={this.state.addModal}
          centered
          onOk={this.handleAdd}
          className="addModal"
          onCancel={() => {
            this.setState({ addModal: false });
          }}

        >
          <AddOrEditVendorCustom
            all_vendors={this.state.all_vendors}
            wrappedComponentRef={(inst) => this.AddForm = inst}
          />


        </Modal>
        <Modal
          title={<BuildModalTitle visible={this.state.editModal} modalClass="editModal"
                                  title={`修改 : ${this.state.editRecord.name}`}/>}
          destroyOnClose
          visible={this.state.editModal}
          centered
          onOk={this.handleEdit}
          className="editModal"
          afterClose={() => {
            afterCloseModal(); // destroyOnClose需要
          }}
          onCancel={() => {
            this.setState({ editModal: false, editRecord: {} });
          }}

        >
          <AddOrEditVendorCustom
            all_vendors={this.state.all_vendors}
            editRecord={this.state.editRecord}
            wrappedComponentRef={(inst) => this.EditForm = inst}
          />

        </Modal>
      </div>
    );
  }
}

const AddPoliciesFormWrap = Form.create()(AddPoliciesForm);
export default connect()(AddPoliciesFormWrap);


